給定一個字符串 s,找到它的第一個不重複字符,並返回它的索引。如果不存在不重複字符,則返回 -1。
from collections import Counter
class Solution:
    def firstUniqChar(self, s: str) -> int:
        hash_map = Counter(s)
        for char in s:
            if hash_map[char] == 1:
                return s.index(char)
        
        return -1
給定兩個字符串 s 和 t,其中 t 是由 s 隨機重排並在隨機位置添加一個字母生成的。請找出 t 中多出來的那個字母。
class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        # 初始化哈希表來計算 s 中每個字符的出現次數
        hash_map = {}
        for char in s:
            hash_map[char] = hash_map.get(char, 0) + 1  # 如果字符存在則增加計數,否則初始化為 1
        # 遍歷 t 中的字符來查找多出來的那個字符
        for char in t:
            if char not in hash_map or hash_map[char] == 0:  # 如果字符不在 hash_map 中或次數為 0
                return char
            hash_map[char] -= 1  # 減少計數